package com.py.credit.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.Column;
import com.py.credit.entity.SharingMetric;
import com.py.credit.entity.SharingMetricInfo;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.SharingMetricsTableFieldEnum;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.SharingMetricService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.exception.ServiceException;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping("/dbMetric")
public class SharingMetricController {

	private final static String FRONT_TABLE_ID = "dbMetricTable";

	@Autowired
	private RemoteBaseService remoteBaseService;

	@Autowired
	private SharingMetricService sharingMetricService;

	@RequestMapping(value = "/getOptionalColumns.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColumns() {

		return new RestServiceResult<List<OptionalColumn>>(SharingMetricsTableFieldEnum.getOptionalColumns());

	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {

		return new RestServiceResult<List<OptionalColumn>>(SharingMetricsTableFieldEnum.getAdvancedConditionColumns());

	}

	@RequestMapping(value = "/getTableList.json")
	public RestServiceResult<List<Map<String, Object>>> getTableList(

			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		String[] configColumns = null;

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo) {

				configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);
			} else {

				ExceptionLogger.error("SharingMetricController#getTableList", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("SharingMetricController#getTableList", "未获取到当前用户信息！");
		}

		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? SharingMetricsTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);

		String[] additionalColumns = { "id" };

		List<Map<String, Object>> tableList = sharingMetricService.getByConditionForPage(showColumns, additionalColumns,
				condition, page);

		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), tableList);

	}

	@RequestMapping(value = "/addShowColumns.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {

		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo) {

				MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID, columns);
			} else {

				ExceptionLogger.error("SharingMetricController#addShowColunms", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("SharingMetricController#addShowColunms", "未获取到当前用户信息！");
		}

		return new RestServiceResult<String>();
	}

	@RequestMapping(value = "/exportList.json")
	public void exportCommoncontentList(
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletResponse response) throws IOException {

		page.setLimit(1000);

		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		List<Map<String, Object>> tableList = sharingMetricService.getByConditionForPage(showColumns, null, condition,
				page);

		List<OptionalColumn> optionalColumns = SharingMetricsTableFieldEnum.getOptionalColumns();

		ExcelUtil.downloadExcel(response, tableList, "公共字段列表", "公共字段列表", showColumns, optionalColumns);

	}

	@RequestMapping(value = "/add.json")
	public RestServiceResult<String> add(SharingMetricInfo sharingMetricInfo, HttpServletRequest request) {

		int count = sharingMetricService.getCountByKId(sharingMetricInfo.getkId());

		if (count > 0) {

			throw new ServiceException("主体已存在");

		}
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

			SysUser userInfo = user.getData();

			if (null != userInfo) {

				sharingMetricInfo.setMantainer(userInfo.getUsername());

			} else {

				ExceptionLogger.error("SharingMetricController#addShowColunms", "未获取到当前用户信息！");
			}

		} else {

			ExceptionLogger.error("SharingMetricController#addShowColunms", "未获取到当前用户信息！");
		}

		sharingMetricService.add(sharingMetricInfo);

		return new RestServiceResult<String>();
	}

	@RequestMapping(value = "/del.json")
	public RestServiceResult<String> del(@RequestParam(value = "ids", defaultValue = "", required = true) String ids) {

		sharingMetricService.del(ids);

		return new RestServiceResult<String>();
	}

	@RequestMapping(value = "/addColumn.json")
	public RestServiceResult<String> addColumn(@RequestParam(value = "id", defaultValue = "", required = true) int id,
			@RequestParam(value = "columns", defaultValue = "", required = true) String columns) {

		List<SharingMetric> parseArray = JSONArray.parseArray(columns, SharingMetric.class);

		sharingMetricService.addColumns(id, parseArray);

		return new RestServiceResult<String>();
	}

	@RequestMapping(value = "/getDbMetricValue.json")
	public RestServiceResult<List<Column>> getDbMetricValue(
			@RequestParam(value = "id", defaultValue = "", required = true) String id, Page page) {

		SharingMetricInfo sharingMetricInfo = sharingMetricService.getMetricInfoById(id);

		List<Column> SharingMetric = sharingMetricService.getSharingColumns(String.valueOf(sharingMetricInfo.getkId()));

		return new RestServiceResult<List<Column>>(page.getTotalCount(), SharingMetric);
	}

	@RequestMapping(value = "/operateDbMetricValue.json")

	public RestServiceResult<String> operateDbMetricValue(
			@RequestParam(value = "infoId", defaultValue = "", required = true) int infoId,
			@RequestParam(value = "addColumn", defaultValue = "", required = true) String addColumn,
			@RequestParam(value = "delColumn", defaultValue = "", required = true) String delColumn,
			@RequestParam(value = "updateColumn", defaultValue = "", required = true) String updateColumn) {

		List<SharingMetric> addColumns = JSONArray.parseArray(addColumn, SharingMetric.class);
		List<SharingMetric> updateColumns = JSONArray.parseArray(updateColumn, SharingMetric.class);
		List<SharingMetric> delColumns = JSONArray.parseArray(delColumn, SharingMetric.class);
		sharingMetricService.updateDbMetrics(infoId, addColumns, updateColumns, delColumns);
		return new RestServiceResult<String>();

	}

	@IgnoreAuthority
	@RequestMapping(value = "/getDbMetricNum.json")
	public RestServiceResult<Integer> operateDbMetricValue(@RequestParam(value = "kId", required = true) String kId) {

		List<Column> sharingColumns = sharingMetricService.getSharingColumns(kId);

		return new RestServiceResult<Integer>(sharingColumns.size());

	}

}
